package com.xuhao.examai.domain.models;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import jakarta.persistence.*;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;

@Data
@Entity
@Table(name = "users")
@NoArgsConstructor
@AllArgsConstructor
public class User implements UserDetails {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(unique = true, nullable = false, length = 50)
	private String username;

	@Column(nullable = false)
	private String password;

	@Column(nullable = false, length = 100)
	private String name;

	@Column(unique = true, length = 100)
	private String email;

	@Column(nullable = false, length = 20)
	@Enumerated(EnumType.STRING)
	private Role role = Role.STUDENT;

	@Column(name = "phone", length = 20)
	private String phone;

	@Column(name = "avatar")
	private String avatar;

	@Column(name = "is_active")
	private Boolean isActive = true;

	@Column(name = "last_login_time")
	private LocalDateTime lastLoginTime;

	@Column(name = "created_at")
	private LocalDateTime createdAt;

	@Column(name = "updated_at")
	private LocalDateTime updatedAt;

	@PrePersist
	protected void onCreate() {
		createdAt = LocalDateTime.now();
		updatedAt = LocalDateTime.now();
	}

	@PreUpdate
	protected void onUpdate() {
		updatedAt = LocalDateTime.now();
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role));
	}

	@Override
	public boolean isAccountNonExpired() {
		return isActive;
	}

	@Override
	public boolean isAccountNonLocked() {
		return isActive;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return isActive;
	}

	@Override
	public boolean isEnabled() {
		return isActive;
	}

	/**
	 * 验证用户数据是否有效
	 */
	public boolean isValid() {
		return username != null && !username.trim().isEmpty()
				&& password != null && !password.trim().isEmpty()
				&& name != null && !name.trim().isEmpty()
				&& email != null && !email.trim().isEmpty();
	}

	/**
	 * 检查用户是否有指定角色
	 */
	public boolean hasRole(Role role) {
		return this.role.equals(role);
	}

	/**
	 * 检查用户是否是管理员
	 */
	public boolean isAdmin() {
		return Role.ADMIN.equals(role);
	}

	/**
	 * 检查用户是否是教师
	 */
	public boolean isTeacher() {
		return Role.TEACHER.equals(role);
	}

	/**
	 * 检查用户是否是学生
	 */
	public boolean isStudent() {
		return Role.STUDENT.equals(role);
	}

	/**
	 * 更新最后登录时间
	 */
	public void updateLastLoginTime() {
		this.lastLoginTime = LocalDateTime.now();
	}

	/**
	 * 用户角色枚举
	 */
	public enum Role {
		ADMIN, TEACHER, STUDENT
	}
}
